const { list, userList, tab } = require("./mock");
const bodyParser = require("body-parser");

module.exports = (app) => {
  app.use(bodyParser.json());
  app.get("/api/list", (req, res) => {
    const { pageCode = 1, pageSize = 10 } = req.query;
    if (pageCode * pageSize <= list.length) {
      res.send({
        code: 200,
        data: list.slice((pageCode - 1) * pageSize, pageCode * pageSize),
        message: "数据请求成功",
      });
    } else {
      res.send({
        code: 400,
        data: null,
        message: "暂无更多数据",
      });
    }
  });

	app.get("/api/tab", (req, res) => {
      res.send({
        code: 200,
        data: tab,
      });
  });

  app.post("/api/login", (req, res) => {
    const { username, password } = req.body;

    const user = userList.find(
      (v) => v.username === username && v.password === password
    );

    if (user) {
      res.send({
        code: 200,
        data: {
          token: "EKDWNELQWNDLQ.WLDMQ;W/LDQ;WDLQWQ" + Math.random(),
          aboutList: user.aboutList,
          username: user.username,
        },
      });
    } else {
      res.send({
        code: 401,
        data: null,
      });
    }
  });

  app.post("/api/list/add", (req, res) => {
    const { title, url, desc } = req.body;

    list.unshift({
      title,
      url,
      desc,
      id: Math.random().toString().slice(2),
    });

    res.send({
      code: 200,
      message: "OK",
    });
  });
};
